package job2;


import java.io.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/*
题目：编写程序，循环接收用户从键盘输入多个字符串，直到输入“end”时循环结束，并将所有已输入的字符串按字典顺序倒序录入到项目下abc.txt中
 */
public class Main {
    public static void main(String[] args) throws IOException {
        List<String> words = readWords();
        System.out.println("您输入的单词为：" + words);
        words.sort(Comparator.reverseOrder()); //java8, 降序排序, 等价于 words.sort((o1, o2) -> o2.compareTo(o1));
        System.out.println("您输入的单词降序排序后的结果为：" + words);
        writeToFile(words, new File("abc.txt"));
    }
    private static void writeToFile(List<String> words, File file) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
        for (String word : words) {
            bufferedWriter.write(word);
            bufferedWriter.newLine();
        }
        bufferedWriter.close();
        System.out.println("成功将单词们写入到文件：" + file.getAbsolutePath());
    }
    /*
        循环接收用户从键盘输入多个字符串，直到输入“end”时循环结束, 注意
        1.不录入end 单词
        2.录入的字符串将删除首尾的空白字符。
        2.不录入全是空白字符的行，由public String trim()定义空白字符
        4.不处理io异常
     */
    private static List<String> readWords() throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        List<String> words = new ArrayList<>();
        System.out.println("请连续输入单词，直到end结束！");
        String line;
        while ((line = bufferedReader.readLine()) != null) {
//          删除首位的空白字符
            line = line.trim();
            if (line.length() > 0) {
                if (line.equals("end")) break;
                words.add(line);
            }
        }
        System.out.println("输入结束");
        bufferedReader.close();
        return words;
    }
}